package calorie.com.calorie.fragment;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ido.ble.BLEManager;
import com.ido.ble.LocalDataManager;
import com.ido.ble.data.manage.database.HealthSport;
import com.lxh.baselibray.dialog.AlertDialog;
import com.lxh.baselibray.mvp.MvpFragment;
import com.lxh.baselibray.util.ObjectUtils;
import com.lxh.baselibray.util.SizeUtils;
import com.lxh.baselibray.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import calorie.com.calorie.R;
import calorie.com.calorie.activity.ScanDeviceActivity;
import calorie.com.calorie.activity.SportStastistticsActivity;
import calorie.com.calorie.constant.Constant;
import calorie.com.calorie.contact.GetAssetsContact;
import calorie.com.calorie.contact.SaveSportDataContact;
import calorie.com.calorie.contact.SingleLoginContact;
import calorie.com.calorie.contact.UserInfoContact;
import calorie.com.calorie.response.ResultDTO;
import calorie.com.calorie.response.User;
import calorie.com.calorie.response.UserInfoResponce;
import calorie.com.calorie.response.UserSport;
import calorie.com.calorie.response.UserSportResponse;
import calorie.com.calorie.util.BLEUpdateBroadcastReceiver;
import calorie.com.calorie.util.StaticValue;
import retrofit2.Response;

/**
 * 运动数据
 */
public class SportDataFragment extends MvpFragment<SaveSportDataContact.SaveSportDataPresent> implements SaveSportDataContact.ISaveSportDataView, UserInfoContact.IUserInfoView {
    @BindView(R.id.level_icon)
    ImageView levelIcon;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_ka)
    TextView tvKa;
    @BindView(R.id.tv_minute)
    TextView tvMinute;
    @BindView(R.id.tv_lenth)
    TextView tvLenth;
    @BindView(R.id.tv_step)
    TextView tvStep;
    @BindView(R.id.tv_hour)
    TextView tvHour;
    @BindView(R.id.tv_synchronous_data)
    public TextView tv_synchronous_data;
    UserInfoContact.UserInfoPresent userInfoPresent;
    SingleLoginContact.SingleLoginPresent singleLoginPresent;
    public static int heartRate = 0;

    Unbinder unbinder;


    @Override
    public void initBeforView(Bundle savedInstanceState) {
        super.initBeforView(savedInstanceState);
        userInfoPresent = new UserInfoContact.UserInfoPresent();
        userInfoPresent.attach(this);


    }

    @Override
    public void initData(Bundle savedInstanceState) {
        BLEUpdateBroadcastReceiver mBroadcastReceiver = new BLEUpdateBroadcastReceiver(tv_synchronous_data);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.lanjing.update");
        context.registerReceiver(mBroadcastReceiver, intentFilter);//注册一个广播
        getAssetsHandler.postDelayed(runnable, 0);
        mPresent.getTodaySportData(context);
        userInfoPresent.getUserInfo(context);
    }

    Handler getAssetsHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mPresent.getAssets(context);//获取余额
            getAssetsHandler.postDelayed(this, 4000);

        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.fragment_sport_data;
    }

    @OnClick({R.id.tv_sport_stastistics, R.id.tv_synchronous_data})
    public void onViewClicked(View view) {
        try {

            switch (view.getId()) {
                case R.id.tv_sport_stastistics:
                    startActivity(new Intent(context, SportStastistticsActivity.class));
                    break;
                case R.id.tv_synchronous_data:
                    if (BLEManager.isConnected() && view.getTag() != null && view.getTag().toString().equals("0")) {
                        getSportData();
                    } else if (view.getTag() != null && view.getTag().toString().equals("1")) {
                        BLEManager.startScanDevices();//重新扫描
                    } else if (view.getTag() != null && view.getTag().toString().equals("2")) {
                        Intent intent = new Intent(context, ScanDeviceActivity.class);
                        startActivity(intent);
                    } else if (view.getTag() != null && view.getTag().toString().equals("3")) {
                        BLEManager.startSyncHealthData();
                        BLEManager.startSyncActivityData();
                        BLEManager.getLiveData();
                        BLEUpdateBroadcastReceiver.bracelet_view.setEnabled(false);
                        BLEUpdateBroadcastReceiver.bracelet_view.setTag(null);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showLongToast(context, "some  mistakes ....");
        }
    }


    @Override
    public void getSaveSportDataResult(Response<UserSportResponse> response) {
        Log.e("SportDataFragment", "server" + response.code());
    }


    @Override
    protected SaveSportDataContact.SaveSportDataPresent createPresent() {
        return new SaveSportDataContact.SaveSportDataPresent((GetAssetsContact.IgetAssets) getActivity());
    }


    public void getSportData() {//获取运动数据
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String[] date = sdf.format(new Date()).split("-");
            HealthSport healthSport = LocalDataManager.getHealthSportByDay(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]));
            if (healthSport == null) {
                ToastUtils.showLongToast(context, "没有运动数据");
                return;
            }
            ToastUtils.showLongToast(context, "同步成功");
            BLEUpdateBroadcastReceiver.bracelet_view.setText("点击刷新数据");
            BLEUpdateBroadcastReceiver.bracelet_view.setTag("3");
            double calorie = healthSport.getTotalCalory();
            tvKa.setText(calorie + "卡");
            int stepNumber = healthSport.getTotalStepCount();
            tvStep.setText(stepNumber + "步");
            double length = healthSport.getTotalDistance();
            double time = healthSport.getTotalActiveTime();
            //  HealthHeartRate healthHeartRate = LocalDataManager.getHealthHeartRateByDay(Integer.parseInt(date[0]), Integer.parseInt(date[1]), Integer.parseInt(date[2]));

            String mileage = (String.format("%.2f", length / 1000));
            tvLenth.setText(mileage + "km");
            tvHour.setText(String.format("%.2f", time / 60) + "min");
           /* if (healthHeartRate != null) {
                heartRate = healthHeartRate.getSilentHeart();
                tvMinute.setText(heartRate + "/min");
            }*/
            if (heartRate != 0) {
                tvMinute.setText(heartRate + "/min");
            }

            //提交现在的运动数据到服务器
            mPresent.saveSportData(calorie, heartRate, stepNumber, length, time, StaticValue.user.getId());
            Log.e("saving...", "");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    AlertDialog alertDialog = null;

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).addDefaultAnimation().setCancelable(true)
                .setContentView(R.layout.dialog_remind)
                .setWidthAndHeight(SizeUtils.dp2px(context, 279), SizeUtils.dp2px(context, 157))
                .setOnClickListener(R.id.bt_start_download, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
        alertDialog = builder.create();
        alertDialog.show();

    }

    @Override
    public void getUserTodaySportData(Response<ResultDTO> response) { //获取当天的运动数据
        Object data = response.body().getData();
        UserSport userSport = null;
        Gson gs = new Gson();
        if (data != null) { //不等于空，代表今天已经提交过数据
            userSport = gs.fromJson(gs.toJson(data), UserSport.class);


            double calorie = userSport.getCalorie();
            tvKa.setText(calorie + "卡");
            int stepNumber = userSport.getStepNumber();
            tvStep.setText(stepNumber + "步");
            double length = userSport.getMileage();
            double time = userSport.getActivityTime();

            String mileage = (String.format("%.2f", length / 1000));
            tvLenth.setText(mileage + "km");
            tvHour.setText(String.format("%.2f", time / 60) + "min");
            double heartRate = userSport.getHeartRate();
            tvMinute.setText(heartRate + "/min");


        } else if (data == null) {
            //晚上18点以后 还是空的  就提示用户同步数据
            Date now = new Date();
            if (now.getHours() >= 18) {
                showDialog();
//                View view = LayoutInflater.from(context).inflate(R.layout.dialog_download, null);
////
////                TextView textView = view.findViewById(R.id.resultView);
////                textView.setText("今天你还没有同步数据,赶紧同步一下吧 ^_^");
////                textView.setTextSize(12);
////                Dialog dialog = new Dialog(context);
////                dialog.setContentView(view);
////                Window window = dialog.getWindow();
////                window.getDecorView().setPadding(0, 0, 0, 0);
////                WindowManager.LayoutParams lp = window.getAttributes();
////                //设置宽高
////                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
////                DisplayMetrics metric = new DisplayMetrics();
////                context.getWindowManager().getDefaultDisplay().getMetrics(metric);
////                lp.height = metric.heightPixels/3;
////                window.setAttributes(lp);
////                dialog.show();
////                AppCompatButton bt_start_download =  view.findViewById(R.id.bt_start_download);
////                bt_start_download.setText("知道了");
////                bt_start_download.setOnClickListener(new View.OnClickListener() {
////                    @Override
////                    public void onClick(View v) {
////                        dialog.dismiss();
////                    }
////                });
            }
        }
    }

    @Override
    public void getUserInfoData(Response<UserInfoResponce> response) {

        if (response.body().getCode() == Constant.SUCCESS_CODE) {
            Gson gs = new Gson();
            Object data2 = response.body().getData();
            StaticValue.user = gs.fromJson(gs.toJson(data2), User.class);//保存用户信息
            UserInfoResponce.DataBean data = response.body().getData();
            if (ObjectUtils.isEmpty(data)) return;
            String levelText = "";

            switch (data.getLevel()) {
                case 0:

                    levelText = "帐号未激活";
                    levelIcon.setVisibility(View.GONE);
                    break;
                case 1:
                    levelText = "菜鸟";
                    levelIcon.setImageResource(R.drawable.level_cainiao);//菜鸟
                    levelIcon.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    levelText = "达人";
                    levelIcon.setImageResource(R.drawable.level_daren);//达人
                    levelIcon.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    levelText = "健将";
                    levelIcon.setImageResource(R.drawable.level_jianjiang);//健将
                    levelIcon.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    levelText = "精英";
                    levelIcon.setImageResource(R.drawable.level_jingying);//精英
                    levelIcon.setVisibility(View.VISIBLE);
                    break;
                case 5:
                    levelText = "教练";
                    levelIcon.setImageResource(R.drawable.level_jiaolian);//教练
                    levelIcon.setVisibility(View.VISIBLE);
                    break;
                case 6:
                    levelText = "大师";
                    levelIcon.setImageResource(R.drawable.level_dashi);//大师
                    levelIcon.setVisibility(View.VISIBLE);
                    break;
                case 7:
                    levelText = "王者";
                    levelIcon.setImageResource(R.drawable.level_wangzhe);//王者
                    levelIcon.setVisibility(View.VISIBLE);
                    break;


            }
            tvLevel.setText(levelText);
        } else {
            ToastUtils.showLongToast(context, response.body().getMsg());
        }
    }

  /*   @Override

   public void getUserInfoData(Response<UserInfoResponce> response) {

        if (response.body().getCode() == Constant.SUCCESS_CODE) {
            Gson gs = new Gson();
            Object data2 = response.body().getData();
            StaticValue.user = gs.fromJson(gs.toJson(data2), User.class);//保存用户信息
            UserInfoResponce.DataBean data = response.body().getData();
            if (ObjectUtils.isEmpty(data)) return;
            String levelText = "";
            switch (data.getLevel()) {
                case 0:
                    levelText = "帐号未激活";
                    break;
                case 1:
                    levelText = "calorie达人";
                    break;
                case 2:
                    levelText = "calorie教练";
                    break;
                case 3:
                    levelText = "calorie大师";
                    break;
                case 4:
                    levelText = "calorie王者";
                    break;
            }
            tvLevel.setText(levelText);
        } else {
            ToastUtils.showLongToast(context, response.body().getMsg());
        }
    }*/

    @Override

    public void onResume() {
        super.onResume();
        userInfoPresent.getUserInfo(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
